const db = require('../database')

module.exports = {
  // 获取所有博客列表
  getAllList() {
    return db.Blog
      .find()
      .select('_id title isPublished tag')
      .sort('time')
      .exec()
  },
  getBlogByHref(href) {
    return db.Blog
      .findOne({href})
      .select('_id')
  },
  // 获取展示用博客
  async getDisplayList(page=1) {
    const limit = 2
    const skip = limit*(page-1)
    const list = await db.Blog
      .find({isPublished: true})
      .select('_id title href')
      .sort('time')
      .limit(limit)
      .skip(skip)
      .exec()
    const count = await db.Blog
    .find({isPublished: true})
    .count()
    return {list, count}
  },
  // 获取博客详情
  async getContent(_id) {
    const blogItem = await db.Blog.findOne({_id})
    if(!blogItem) throw new Error('该blog不存在!')
    return db.Blog
      .findOne({_id})
      .populate('tag', 'name _id')
      .exec() 
  },
  add(data){
    const model = new db.Blog(data)
    return model.save()
  },
  update(id, data) {
    console.log(data)
    return db.Blog
      .where({_id: id})
      .update(data)
      .exec()
  },
  delete(id) {
    return db.Blog
      .where({_id: id})
      .remove()
  },
  findByTitle(search) {
    return db.Blog
      .where({ title: new RegExp(`${search}`, 'mi') })
      .select('_id title isDraft')
      .exec() 
  },
  async addTag(blogId, tagId) {
    // 先判断该tag和blog存不存在
    const tagItem = await db.Tag.findOne({_id:tagId}).select('blog')
    if(!tagItem) throw new Error('该tag不存在!')
    const blogItem = await db.Blog.findOne({_id:blogId}).select('tag')
    if(!blogItem) throw new Error('该blog不存在!')    
    // 给tag加上博客
    const blogs = tagItem.blog
    if(blogs.indexOf(blogId) === -1) {
      blogs.push(blogId)
      await db.Tag
      .findOne({_id: tagId})
      .update({blog: blogs})
    }
    // 给博客加上tag    
    const tags = blogItem.tag
    if(tags.indexOf(tagId) > -1) throw new Error('blog已存在该tag!')
    tags.push(tagId)
    await db.Blog
    .findOne({_id: blogId})
    .update({tag: tags})
    .exec()
  },
  async removeTag(blogId, tagId) {
    // 先判断该tag和blog存不存在
    const tagItem = await db.Tag.findOne({_id: tagId});
    if(!tagItem) throw new Error('该tag不存在!')
    const blogItem = await db.Blog.findOne({_id: blogId});
    if(!blogItem) throw new Error('该blog不存在!')
    // 去掉博客的tag    
    const tags = blogItem.tag
    const tagIndex = tags.indexOf(tagId)
    if(tagIndex === -1) throw new Error('blog不存在该tag!')
    tags.splice(tagIndex, 1)
    blogItem.tag = tags;
    await blogItem.save();
    // 去掉tag中的blog
    const blogs = tagItem.blog    
    const blogIndex = blogs.indexOf(blogId)
    if(blogIndex !== -1) {
      blogs.splice(blogIndex, 1)
      // 若tag中无blog则删除tag
      if(blogs.length) {
        tagItem.blog = blogs;
        await tagItem.save();
      }
      else {
        await tagItem.remove();
      }
    } 
  }
}